import React, { useState, useEffect } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  message, 
  Checkbox,
  Divider,
  Space
} from 'antd';
import { 
  UserOutlined, 
  LockOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import request from '@/utils/request';
import { login, type LoginParams } from '../api/login';
import { getRedirectPath, clearRedirectPath } from '../config/authConfig';
import './Login.css';

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const navigate = useNavigate();

  // 检查用户是否已经登录
  useEffect(() => {
    const token = localStorage.getItem('token');
    if (token) {
      // 如果已经有token，跳转到原本想访问的页面或首页
      const redirectPath = getRedirectPath();
      navigate(redirectPath, { replace: true });
    }
  }, [navigate]);

  // 处理登录
  const handleLogin = async (values: LoginParams) => {
    setLoading(true);
    try {
      const response = await login(values);
      if (response.code === 200) {
        message.success('登录成功');
        // 保存token到localStorage
        if (response.data?.token) {
          localStorage.setItem('token', response.data.token);
          request.setToken(response.data.token);
        }
        // 保存用户信息到localStorage
        if (response.data?.user) {
          localStorage.setItem('user', JSON.stringify(response.data.user));
        }
        
        // 获取重定向路径
        const redirectPath = getRedirectPath();
        clearRedirectPath();
        
        // 跳转到原本想访问的页面或首页
        navigate(redirectPath, { replace: true });
      } else {
        message.error(response.message || '登录失败');
      }
    } catch (error) {
      message.error('登录失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  // 跳转到注册页
  const goToRegister = () => {
    navigate('/register');
  };

  return (
    <div className="login-container">
      <div className="login-background">
        <div className="login-content">
          <Card className="login-card">
            <div className="login-header">
              <h1 className="login-title">地面应用系统</h1>
              <p className="login-subtitle">数据管理与服务系统</p>
            </div>
            <div className="login-form-header">
              <h2 className="login-form-title">登录</h2>
            </div>

            <Form
              form={form}
              name="login"
              onFinish={handleLogin}
              autoComplete="off"
              size="large"
              layout="vertical"
            >
              <Form.Item
                label="账号"
                name="user"
                rules={[
                  { required: true, message: '请输入账号' },
                  { min: 3, message: '账号至少3位字符' }
                ]}
              >
                <Input
                  placeholder="请输入账号"
                  autoComplete="username"
                />
              </Form.Item>

              <Form.Item
                label="密码"
                name="pwd"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码至少6位字符' }
                ]}
              >
                <Input.Password
                  placeholder="请输入密码"
                  autoComplete="current-password"
                />
              </Form.Item>



              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  className="login-button"
                  loading={loading}
                  block
                >
                  登录
                </Button>
              </Form.Item>

              <Divider plain>或</Divider>

              <Form.Item>
                <Button
                  type="default"
                  className="register-button"
                  onClick={goToRegister}
                  block
                >
                  注册
                </Button>
              </Form.Item>
            </Form>


          </Card>
        </div>
      </div>
    </div>
  );
};

export default Login; 